//
//  LoginAuthViewController.m
//  JmzGo
//
//  Created by apple  on 2017/9/11.
//  Copyright © 2017年 金拇指. All rights reserved.
//

#import "LoginAuthViewController.h"

@interface LoginAuthViewController ()<UITextFieldDelegate,UIWebViewDelegate>
//返回按钮
@property (nonatomic, strong) UIBarButtonItem *backItem;

@property (nonatomic, strong) UIView *topView;

@property (nonatomic, strong) UITextField *userNameField;
@property (nonatomic, strong) UITextField *codeField;
@property (nonatomic, strong) UIButton *getCodeButton;
@property (nonatomic, strong) UIButton *authButton;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, assign) BOOL success;

@end

@implementation LoginAuthViewController

- (UIWebView *)webView
{
    if (!_webView) {
        _webView = [[UIWebView alloc] init];
    }
    
    return _webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = NO;
//    self.navigationItem.title = @"输入手机号，完成验证";
    
    _success = NO;
    [self addLeftButton];
    
    [self initMainView];
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到view上
    [self.view addGestureRecognizer:tapGestureRecognizer];
    
    NSURL *url = [NSURL URLWithString:@"http://weibo.com"];//http://weibo.com
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
    self.webView.delegate = self;
    
}

- (void)initMainView
{
    _topView = [[UIView alloc] init];
    _topView.backgroundColor = [UIColor hexColor:@"63B8FF"];
    [self.view addSubview:_topView];
    [_topView mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.equalTo(self.view);
        make.width.equalTo(self.view);
        make.height.offset(ScreenH);
    }];
    
    UILabel *phoneLabel = [UILabel new];
    phoneLabel.textColor = [UIColor whiteColor];
    phoneLabel.text = @"手机号码:";
    phoneLabel.font = [UIFont systemFontOfSize:18];
    [_topView addSubview:phoneLabel];
    [phoneLabel mas_makeConstraints:^(MASConstraintMaker *make){
        make.topMargin.offset(20);
        make.leftMargin.offset(10);
        make.width.offset(90);
        make.height.offset(40);
    }];
    
    _userNameField = [UITextField new];
    _userNameField.delegate = self;
    _userNameField.returnKeyType = UIReturnKeyNext;
    _userNameField.backgroundColor = [UIColor whiteColor];
    _userNameField.placeholder = @"请输入手机号码";
    _userNameField.keyboardType = UIKeyboardTypePhonePad;
    [_userNameField setValue:[NSNumber numberWithInt:7] forKey:@"paddingLeft"];
    [_topView addSubview:_userNameField];
    [_userNameField mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.equalTo(phoneLabel.mas_bottom);
        make.left.equalTo(phoneLabel.mas_left);
        make.width.offset(ScreenW - 20);
        make.height.offset(40);
    }];
    
    UILabel *codeLabel = [UILabel new];
    codeLabel.textColor = [UIColor whiteColor];
    codeLabel.text = @"验证码:";
    codeLabel.font = [UIFont systemFontOfSize:18];
    [_topView addSubview:codeLabel];
    [codeLabel mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.equalTo(_userNameField.mas_bottom).offset(5);
        make.leftMargin.offset(10);
        make.width.offset(90);
        make.height.offset(40);
    }];
    
    _codeField = [UITextField new];
    _codeField.delegate = self;
    _codeField.returnKeyType = UIReturnKeyDone;
    _codeField.backgroundColor = [UIColor whiteColor];
    _codeField.placeholder = @"请输入验证码";
    _codeField.keyboardType = UIKeyboardTypeNumberPad;
    [_codeField setValue:[NSNumber numberWithInt:7] forKey:@"paddingLeft"];
    [_topView addSubview:_codeField];
    [_codeField mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.equalTo(codeLabel.mas_left);
        make.top.equalTo(codeLabel.mas_bottom);
        make.width.offset(120);
        make.height.offset(40);
    }];
    
    
    _getCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _getCodeButton.backgroundColor = [UIColor whiteColor];
    [_getCodeButton setTitle:@"点击获取" forState:UIControlStateNormal];
    [_getCodeButton setTitleColor:[UIColor hexColor:@"63B8FF"] forState:UIControlStateNormal];
    _getCodeButton.layer.cornerRadius = 20;
    [_getCodeButton addTarget:self action:@selector(getPhoneCode) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:_getCodeButton];
    [_getCodeButton mas_makeConstraints:^(MASConstraintMaker *make){
        make.centerY.equalTo(_codeField.mas_centerY);
        make.left.equalTo(_codeField.mas_right).offset(10);
        make.width.offset(110);
        make.height.offset(40);
    }];
    
    _authButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _authButton.backgroundColor = [UIColor whiteColor];
    [_authButton setTitle:@"登录认证" forState:UIControlStateNormal];
    [_authButton setTitleColor:[UIColor hexColor:@"63B8FF"] forState:UIControlStateNormal];
    _authButton.layer.cornerRadius = 20;
    [_authButton addTarget:self action:@selector(gotoAuth) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:_authButton];
    [_authButton mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.equalTo(_codeField.mas_bottom).offset(30);
        make.centerX.equalTo(_topView.mas_centerX);
        make.width.offset(ScreenW/3*2);
        make.height.offset(40);
    }];

}

-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

#pragma mark - UITextField回调
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _userNameField) {
        [_codeField becomeFirstResponder];
    }else if (textField == _codeField) {
        [textField resignFirstResponder];
    }
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UIWebViewDelegate 回调
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    [webView stringByEvaluatingJavaScriptFromString:@"checkAppLoad();"];
    NSString *url = request.URL.absoluteString;
    NSLog(@"--->shouldLoadURL:%@",url);
    if ([url rangeOfString:@"wifi.jmzgo.com"].location != NSNotFound) {
        NSString *token = [Utile getParamFromURL:Vtoken webaddress:url];
        NSString *guid = [Utile getParamFromURL:Guid webaddress:url];
        
        NSString *aptype = @"";
        if([url rangeOfString:@"/Treebear/"].location != NSNotFound)
        {
            aptype = _authType = Treebear;
        }else {
            aptype = _authType = SundRay;
        }
        
        //if([url rangeOfString:@"/SundRay/"].location != NSNotFound)
        //        NSString *aptype = [Utile getParamFromURL:ApType webaddress:url];
        
        NSLog(@"--->获取到的参数：token:%@  \nguid:%@  \naptyoe:%@",token,guid,aptype);
        
        [StoreUtil saveVtoken:token withGuid:guid withApType:aptype];
        
        return NO;
        
    }else if([url rangeOfString:@"portal.witown.com"].location != NSNotFound) {
        NSString *token = [Utile getParamFromURL:Vtoken webaddress:url];
        NSString *guid = [Utile getParamFromURL:Guid webaddress:url];
        NSString *aptype = Treebear;
        
        [StoreUtil saveVtoken:token withGuid:guid withApType:aptype];
    }else if([url rangeOfString:@"auth.wifi.com"].location != NSNotFound) {
        NSString *token = [Utile getParamFromURL:Vtoken webaddress:url];
        NSString *guid = [Utile getParamFromURL:Guid webaddress:url];
        NSString *aptype = SundRay;
        
        [StoreUtil saveVtoken:token withGuid:guid withApType:aptype];
    }
    
    return YES;
}

- (void)getPhoneCode
{
    NSString *value = _userNameField.text;
    if (value.length == 0) {
        NSLog(@"请输入手机号码进行登录认证");
        [Utile showToast:self.view withText:@"请输入手机号码"];
        return;
    }
    
    NSLog(@"获取手机验证码");
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:value,param_tel, nil];
    [HttpClient requestJson:kUrlSendSMSUrl params:params success:^(NSDictionary *data){
        [Utile showToast:self.view withText:data[@"msg"]];
        NSLog(@"获取到的短信验证码：%@",data);
    } failure:^(NSError *error){
        NSLog(@"获取验证码错误：%@",error);
        [Utile showToast:self.view withText:@"验证码发送失败"];
    }];
    
    [self openCountdown];
}

- (void)gotoAuth
{
    NSLog(@"进行认证");
    NSString *value = _userNameField.text;
    NSString *code = _codeField.text;
    if (value.length == 0) {
        NSLog(@"请输入手机号码进行登录认证");
        [Utile showToast:self.view withText:@"请输入手机号码"];
    }else if (code.length == 0){
        NSLog(@"请输入验证码");
        [Utile showToast:self.view withText:@"请输入验证码"];
    }else {
        
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:value,param_user,code,param_code, nil];
        
        [HttpClient requestJson:kUrlAddUserUrl params:params success:^(NSDictionary *data){
            //1=注册成功，2=注册失败，3=注册过了,0=验证码过期,4=验证码不正确,5=手机号不正确
            //增加确保后台返回的数据类型导致崩溃
            if ([data isKindOfClass:[NSData class]]) {
                
                data = [NSJSONSerialization JSONObjectWithData:(id)data options:NSJSONReadingMutableLeaves error:nil];
                NSLog(@"获取WIFi密码返回的重新解析后的信息：%@",data);
                
            }

            NSLog(@"注册结果：%@",data);
            NSInteger msg = [data[@"msg"] integerValue];
            if (msg == 1 || msg == 3) {
                NSLog(@"注册成功");
                
                if ([Treebear isEqual:_authType]) {
                    [self submitWiFiAllow];
                }else if ([SundRay isEqual:_authType]){
                    [self submitAuth:value];

                }
                
//                [StoreUtil saveUserPhone:value];
            }else if(msg == 0){
                NSLog(@"验证码过期");
                [Utile showToast:self.view withText:@"验证码过期"];
            }else if(msg == 2){
                NSLog(@"注册失败");
                [Utile showToast:self.view withText:@"验证失败"];
            }else if(msg == 4){
                NSLog(@"验证码不正确");
                [Utile showToast:self.view withText:@"验证码不正确"];
            }else if(msg == 5){
                NSLog(@"手机号不正确");
                [Utile showToast:self.view withText:@"手机号不正确"];
            }
        } failure:^(NSError *error){
            NSLog(@"注册失败：%@",error);
        }];
        
    }
    
}

#pragma mark - 请求树熊WiFi网络上网
- (void)submitWiFiAllow
{
    if ([StoreUtil getVtoken] == nil) {
        [Utile showToast:self.view withText:@"Token为nil"];
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:[StoreUtil getVtoken],param_token,_userNameField.text,param_strguid, nil];
    
    [HttpClient requestJson:kUrlGetWiFiAllow params:params success:^(NSDictionary *data) {
        NSLog(@"--->请求上网的返回：%@",data);
        NSInteger msg = [data[@"code"] integerValue];
        if (msg == 1) {
            [self submitSaveUserLocation];
        }else if (msg == 0) {
            [Utile showToast:self.view withText:data[@"msg"]];
        }
    } failure:^(NSError *error){
        NSLog(@"请求上网出错了:%@",error);
        [Utile showToast:self.view withText:[NSString stringWithFormat:@"请求放行出错：%@",error.description]];
    }];
}

#pragma mark - 提交认证到信锐接口
- (void)submitAuth:(NSString *)phone
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd-HH:mm:ss"];
    NSDate *datenow = [NSDate date];
    NSString *time = [formatter stringFromDate:datenow];
    NSString *str = [NSString stringWithFormat:@"n=%@&u=%@&t=%@",phone,phone,time];
    NSString *encryptStr = [NSString stringWithFormat:@"%@&l=%ld",str,str.length];
    NSString *encrypt = [FormUtil convertStringToHexStr:encryptStr];
    NSLog(@"请求的参数:%@  \n加密后的16进制：%@",encryptStr,encrypt);
    // 请求地址
    NSString* url = [NSString stringWithFormat:@"%@?href=%@&id=%@", kUrlSundRayAuthUrl,encrypt,SundRayID];
    NSLog(@"开始请求");
    [HttpClient requestGet:url params:nil success:^(NSObject *response){
        NSLog(@"success:%@",response);
        [self submitSaveUserLocation];
       
        
    } failure:^(NSError *error){
        if (error.code == -1001) {
            NSLog(@"请求超时");
            [Utile showToast:self.view withText:@"认证超时"];
            
        }
    }];
    
}

- (void)popSelfController
{
    self.hidesBottomBarWhenPushed = NO;
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (UIBarButtonItem *)backItem
{
    if (!_backItem) {
        _backItem = [[UIBarButtonItem alloc] initWithTitle:@"< 返回   " style:UIBarButtonItemStylePlain target:self action:@selector(popSelfController)];
    }
    
    return _backItem;
}

- (void)addLeftButton
{
    self.navigationItem.leftBarButtonItem = self.backItem;
}

// 开启倒计时效果
- (void)openCountdown
{
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [self.getCodeButton setTitle:@"重新发送" forState:UIControlStateNormal];
                [self.getCodeButton setTitleColor:[UIColor hexColor:@"63B8FF"] forState:UIControlStateNormal];
                self.getCodeButton.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [self.getCodeButton setTitle:[NSString stringWithFormat:@"%.2ds", seconds] forState:UIControlStateNormal];
                [self.getCodeButton setTitleColor:[UIColor hexColor:@"B5B5B5"] forState:UIControlStateNormal];
                self.getCodeButton.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

- (void)submitSaveUserLocation
{
    NSDictionary *locationDic = [StoreUtil getUserLocation];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NetWordUtil fetchWiFiName],param_ssid,locationDic[param_lng],param_lng,locationDic[param_lat],param_lat,[StoreUtil getGuid],param_strGuid, nil];
    [HttpClient requestJson:kUrlSaveUserLocation params:params success:^(NSDictionary *data){
        
        if ([data isKindOfClass:[NSData class]]) {
            
            data = [NSJSONSerialization JSONObjectWithData:(NSData*)data options:NSJSONReadingMutableLeaves error:nil];
            
        }
        NSInteger msg = [data[@"msg"] integerValue];
        if (msg == 1) {
            NSLog(@"保存用户SSID成功");
           [Utile showToast:self.view withText:@"签到认证成功，可以上网了"];
            [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(TimeAction) userInfo:nil repeats:YES];
//            [NSTimer scheduledTimerWithTimeInterval:2.5 repeats:NO block:^(NSTimer *timer){
//                [self popSelfController];
//            }];
            [self submitSSIDMacToServer];
        }
        
    } failure:^(NSError *error){
        [Utile showToast:self.view withText:error.description];
    }];
}

- (void)TimeAction
{
    [self popSelfController];
}

#pragma mark- 连接上WiFi后，将SSID和路由器的Mac传给服务器，更新热点坐标
- (void)submitSSIDMacToServer
{
    NSDictionary *location = [StoreUtil getUserLocation];
    NSString *point = [NSString stringWithFormat:@"%@,%@",location[param_lng],location[param_lat]];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NetWordUtil fetchWiFiName],param_ssid,point,param_point,[NetWordUtil getWiFiMac],param_bssid, nil];
    [HttpClient requestPost:kUrlUpdateWifiLocationUrl params:params success:^(NSInteger result){
        NSLog(@"----》更新SSID坐标地址成功：%ld",result);
        
    } failure:^(NSError *error){
        NSLog(@"更新SSID坐标和Mac失败：%@",error);
        
        NSLog(@"更新SSID坐标和Mac失败11111:%@",[Utile transErrorInfo:error]);
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
